package utils

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

const AccessTokenClaimsKey = "g83LecmjyxUtjVB41T+"

func GenerateAccessToken(user string, accessTokenTimeout uint64) (accessToken string, expiresAt int64, err error) {

	t := time.Now()

	expires := t.Add(time.Duration(accessTokenTimeout) * time.Hour)

	expiresAt = expires.Unix()

	if accessToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
		ExpiresAt: jwt.NewNumericDate(expires),
		IssuedAt:  jwt.NewNumericDate(t),
		NotBefore: jwt.NewNumericDate(t),
		Issuer:    "long",
		Subject:   user,
		ID:        GenerateUUID(),
	}).SignedString([]byte(AccessTokenClaimsKey)); err != nil {
		return "", 0, err
	}
	return
}

// AccessTokenVerify token 验证
// @param token 待验证的 token 串
// @return *AccessTokenClaims 解析出的信息
// @return bool 是否过期
// @return error 错误详情
func AccessTokenVerify(token string) (*jwt.RegisteredClaims, bool, error) {
	claims, err := jwt.ParseWithClaims(token, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(AccessTokenClaimsKey), nil
	})
	switch {
	case claims.Valid:
		return claims.Claims.(*jwt.RegisteredClaims), false, nil
	case errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet):
		return nil, true, errors.New("认证token过期")
	default:
		return nil, false, errors.New("非法的token")
	}
}
